/*
 *  @Title SftpClientUtils.java
 *  @Package： com.phoenix.core.util
 *  Copyright (c) 2017 by 江苏深南互联网金融信息服务有限公司  All right reserved
 */
package com.phoenix.core.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import com.phoenix.core.logger.SimpleLogger;

/**
 * @ClassName SftpClientUtils
 * @Description 类注释
 * @author liuwb
 * @version 1.0
 * @date 2017年7月29日
 */
public class SftpClientUtils {

	private static SimpleLogger logger = SimpleLogger.getLogger(SftpClientUtils.class);

	private Session sshSession;
	private ChannelSftp sftp;

	/** 关闭ftp连接 */
	public void closeConnect() {
		if (sftp != null && sftp.isConnected()) {
			sftp.disconnect();
		}
		if (sshSession != null && sshSession.isConnected()) {
			sshSession.disconnect();
		}
	}

	/**
	 * 连接sftp服务器
	 * 
	 * @param host主机
	 * @param port端口
	 * @param username用户名
	 * @param password密码
	 * @return
	 */
	public SftpClientUtils(String host, int port, String username, String password) {
		try {
			createSession(host, port, username, password);
			Channel channel = sshSession.openChannel("sftp");
			channel.connect();
			sftp = (ChannelSftp) channel;
			if (logger.isDebugEnabled()) {
				logger.debug("Connected to " + host + ".");
			}
		} catch (Exception e) {
			logger.error("SftpClientUtils exception:", e);
		}
	}

	private void createSession(String host, int port, String username, String password) throws JSchException {
		JSch jsch = new JSch();
		jsch.getSession(username, host, port);
		sshSession = jsch.getSession(username, host, port);
		if (logger.isDebugEnabled()) {
			logger.debug("Session created.");
		}
		sshSession.setPassword(password);
		Properties sshConfig = new Properties();
		sshConfig.put("StrictHostKeyChecking", "no");
		sshSession.setConfig(sshConfig);
		sshSession.connect();
		if (logger.isDebugEnabled()) {
			logger.debug("Session connected...Opening Channel...");
		}
	}

	/**
	 * 上传文件
	 * 
	 * @param directory上传的目录
	 * @param uploadFile要上传的文件
	 * @param sftp
	 */
	public void upload(String directory, String uploadFile) {
		try {
			sftp.cd(directory);
			File file = new File(uploadFile);
			sftp.put(new FileInputStream(file), file.getName());
		} catch (Exception e) {
			logger.error("upload exception:", e);
		}
	}

	public void checkDirectory(String directory) {
		try {
			sftp.ls(directory);
		} catch (SftpException e) {
			try {
				sftp.mkdir(directory);
				sftp.chmod(666, directory);
			} catch (SftpException e1) {
			}
			logger.error("没有找到相应的目录,执行mkdir 命令创建目录:"+directory);
		}

	}

	/**
	 * 下载文件
	 * 
	 * @param directory下载目录
	 * @param downloadFile下载的文件名
	 * @param saveFile存在本地的路径
	 * @param sftp
	 */
	public boolean download(String directory, String downloadFile, String saveFile) {
		try {
			sftp.cd(directory);
			File file = new File(saveFile);
			sftp.get(downloadFile, new FileOutputStream(file));
			return file.exists();
		} catch (Exception e) {
			logger.error("download exception:", e);
		}
		return Boolean.FALSE;
	}

	/**
	 * 下载文件,获取文件IO流
	 * 
	 * @param directory下载目录
	 * @param downloadFile下载的文件名
	 */
	public InputStream download(String directory, String downloadFile) {
		try {
			sftp.cd(directory);
			return sftp.get(downloadFile);
		} catch (Exception e) {
			logger.error("download exception:", e);
		}
		return null;
	}

	/**
	 * 下载文件,分行符号,为系统分行符
	 * 
	 * @param directory下载目录
	 * @param downloadFile下载的文件名
	 * @param charset字符,可空
	 */
	public String downloadAsString(String directory, String downloadFile, String charset) {
		StringBuilder sb = new StringBuilder();
		InputStream is = null;
		BufferedReader fileReader = null;
		String line = System.getProperty("line.separator");
		try {
			is = this.download(directory, downloadFile);
			if (charset == null || charset.length() == 0) {
				fileReader = new BufferedReader(new InputStreamReader(is));
			} else {
				fileReader = new BufferedReader(new InputStreamReader(is, charset));
			}
			String lines = null;
			while ((lines = fileReader.readLine()) != null) {
				sb.append(lines).append(line);
			}
		} catch (Exception e) {
			logger.error("downloadAsString exception:", e);
		} finally {
			try {
				fileReader.close();
			} catch (Exception e) {
				logger.error("downloadAsString close exception:", e);
			}
		}
		return sb.toString();
	}

	public static void main(String[] args) {
		SftpClientUtils u = new SftpClientUtils("163.53.88.26", 22000, "tzp", "tzp@2015");
		String directory = "C:" + File.separator;// 下载到本地的存储路径
		// u.upload(directory,
		// "product_$INSTID_fix_receive_201708161751_seq.req.txt");
		u.download(directory, "product_$INSTID_fix_receive_201708161751_seq.req.txt", "201708161751_seq.req.txt");
	}
}
